import Web3 from 'web3'
import file from '@/dapp/config/file.js'
import { removeAddress, removeToken, removeActive } from '@/config/storage.js'
var {
	chainId
} = file
export default {
	isConnect: false,
	account: null,
	chainId: null,
	web3: null,
	_init() {
		this.account = this.chainId = this.web3 = null
		this.isConnect = false
	},
	async connectWeb3() {
		let _this = this
		if (window.ethereum) {
			try {
				await window.ethereum.request({
					method: 'wallet_switchEthereumChain',
					params: [{
						chainId: Web3.utils.numberToHex(chainId) // 目标链ID
					}]
				})
			} catch (e) {
				if (e.code == 4902) { //添加链
					try {
						await window.ethereum
							.request({
								method: 'wallet_addEthereumChain',
								params: [{
									chainId: '0x38',
									chainName: 'BSC',
									nativeCurrency: {
										name: 'BNB',
										symbol: 'BNB',
										decimals: 18,
									},
									rpcUrls: ['https://bsc-dataseed.binance.org/'],
									blockExplorerUrls: ['https://bscscan.com/'],
								}, ],
							})
					} catch (e) {

					}
				} else if (e.code === 4001) {
					return
				}
			}
		}
		const func = async function(accounts) {
			_this.address = accounts[0];
			if (_this.isConnect) {
				window.location.reload()
			}
		}
		let web3Provider;
		if (window.ethereum) {
			window.ethereum.autoRefreshOnNetworkChange = false
			//监听账号切换
			window.ethereum.on("accountsChanged", func)
			// 监听链id变化
			window.ethereum.on("chainChanged", chainId1 => {
				_this.chainId = chainId1;
				func([_this.account]);
			})
			web3Provider = window.ethereum;
			try {
				await window.ethereum.enable();
			} catch (error) {
				uni.showToast({
					title: "Wallet connect error",
					icon: 'error'
				})
				return
			}
		} else {
			uni.showToast({
				title: "Please install Metamask",
				icon: 'error'
			})
			return
		}
		_this.web3 = new Web3(web3Provider);
		_this.web3.eth.getAccounts(function(error, result) {});
		_this.isConnect = window.ethereum.selectedAddress || null || false;
		_this.account = _this.web3.utils.toChecksumAddress(window.ethereum.selectedAddress) || null
		_this.chainId = window.ethereum.networkVersion || null
		if (_this.chainId != chainId) return; // 链不对,就不去连接合约了
		if (_this.account) {
			
		}
		return _this.account;
	},
}
